package com.admin.web.config.shiro;

import com.fegin.bean.admin.MenuResourse;
import com.fegin.bean.admin.AdminUser;
import com.fegin.client.admin.UserFegin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 张子艺
 * @packge com.controller.config.shiro
 * @data 2019-01-08 11:42
 * @project Currency
 */
public class ShiroRealm extends AuthorizingRealm {
    //lazy注解 延迟注入  否则该service里的事务等注解会失效
    @Autowired
    @Lazy
    UserFegin userService;

    //鉴权
    //doGetAuthorizationInfo()是权限控制，
    // 当访问到页面的时候，
    // 使用了相应的注解或者shiro标签才会执行此方法否则不会执行
    // ，所以如果只是简单的身份认证没有权限的控制的话，
    // 那么这个方法可以不进行实现，
    // 直接返回null即可。
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //此方法中的值 为doGetAuthenticationInfo 存入的user
        AdminUser user = (AdminUser) principalCollection.getPrimaryPrincipal();

        //从shiro中取出登陆成功后的用户信息   并把角色名 给shiro控制
        //权限
        Set<String> roleSet = new HashSet<String>();
        roleSet.add("role:" + user.getRole().getRoleName());
        simpleAuthorizationInfo.addRoles(roleSet);
        List<MenuResourse> menuResourse = user.getRole().getMenuResourses();


        for (int i = 0; i < menuResourse.size(); i++) {
            if(menuResourse.get(i).getMenuType()==2){
                simpleAuthorizationInfo.addStringPermission("button:" + menuResourse.get(i).getMenuName());
            }
            simpleAuthorizationInfo.addStringPermission("menu:" + menuResourse.get(i).getMenuName());
        }


        return simpleAuthorizationInfo;
    }

    //登陆调用 subject.login(token);会调用该方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String requestUserName = token.getUsername();
        String requestPassWord = new String(token.getPassword());

        AdminUser user = userService.login(requestUserName,requestPassWord);

        //这里只需要传入 数据库中查出的对象和 密码即可
        SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(
                user,  //这里传对象
                user.getPassword(),
                getName()
        );
        return authorizationInfo;
    }


}
